package org.NooLab.itexx.app.gui.handlers;


import java.awt.Color;
import java.awt.Component;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JComponent;
import javax.swing.JEditorPane;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JWindow;
import javax.swing.UIManager;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;


import org.NooLab.itexx.ITexxWindowCommons;
import org.NooLab.itexx.app.gui.TransparentTextPane;
import org.NooLab.itexx.app.gui.definition.ITexxWindowGuiIntf;
import org.NooLab.utilities.logging.PrintLog;
import org.apache.commons.collections.BidiMap;
import org.apache.commons.collections.bidimap.DualHashBidiMap;
import org.jdesktop.swingx.plaf.nimbus.NimbusLookAndFeelAddons;

public class ResultPanelPopupMenu {


	ITexxWindowGuiIntf windowGui;
	
	JWindow wrappingwindow ;
	ITexxWindowCommons appCommons;
	JPopupMenu resultPanelsjPopupMenu ;
	
	JMenuItem[] popupItems = new JMenuItem[5];
	ItemHandler handler = null;


	BidiMap mappedItems = new DualHashBidiMap();
	
	private PrintLog out;

	private Component wwPopup;

	private int clickedPanelIndex;

	private int wwLastWidth = 50;
	private int wwLastHeight = 50 ;
	
	
	// ========================================================================
	public ResultPanelPopupMenu(ITexxWindowGuiIntf gui){
		windowGui = gui;
		appCommons = windowGui.getTexxWindowApp().getAppCommons();
		out = appCommons.out;
		
		wrappingwindow = new JWindow();

		wrappingwindow.setVisible(false);
		wrappingwindow.setSize(1, 1);
	    wrappingwindow.setLocation(100, 100);
	    
	    wrappingwindow.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseExited(MouseEvent evt) {
				// System.err.println(" - - - - mouse exited wrappingwindow");
			}
			@Override
			public void mouseEntered(MouseEvent evt) {
				// System.err.println(" - - - - mouse entered wrappingwindow");
			}
		}) ;
	    
	    JMenu wmenu = new JMenu();
	    
	   // wrappingwindow.setAlwaysOnTop(true);
	    
	    wrappingwindow.getContentPane().setBackground( new Color(0.94f,0.94f,0.98f,0.51f));
	    wrappingwindow.setBackground( new Color(0.94f,0.94f,0.98f,0.51f));
	    
	    
	    
	    // UIManager.setLookAndFeel(arg0);
	    // UIManager.put("PopupMenuUI", NimbusLookAndFeelAddons.class.getCanonicalName());
	}
	// ========================================================================
	
	public void hide(){
		
		if (wrappingwindow !=null){
			wrappingwindow.setVisible(false) ;
			wrappingwindow.setSize(0, 0);		
		}
		
		// the combipanel to repaint
		appCommons.getPanelProducer().getPanels().getItem(clickedPanelIndex).repaint();
		
	}
	
	public void create(){
	
		// setComponentPopupMenu(jPanelScrollDummy, getResultPanelsjPopupMenu());
		// if(resultPanelsjPopupMenu == null)
		
		
		// resultPanelsjPopupMenu.$
		JPopupMenu.setDefaultLightWeightPopupEnabled(false) ;
		resultPanelsjPopupMenu = new JPopupMenu() ;
		resultPanelsjPopupMenu.setLightWeightPopupEnabled(false);
		
		PopupMenuListener popupMenuListener = new RPanelMenuListener();
		resultPanelsjPopupMenu.addPopupMenuListener(popupMenuListener);
		
		resultPanelsjPopupMenu.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseExited(MouseEvent evt) {
				// System.err.println(" - - - - mouse exited popup");
			}
			@Override
			public void mouseEntered(MouseEvent evt) {
				// // System.err.println(" - - - - mouse entered popup");
			}
		}) ;
		
		
		resultPanelsjPopupMenu.addFocusListener(new FocusAdapter() {
			public void focusGained(FocusEvent evt) {
				// out.print(2, "- - - - -   popup gained focus... ");
			}
			public void focusLost(FocusEvent evt) {
				// out.print(2, "- - - - -   popup lost focus... ");
			}
		});

		
		resultPanelsjPopupMenu.setOpaque(true);
		Color bc = resultPanelsjPopupMenu.getBackground();
		
		resultPanelsjPopupMenu.setBackground( new Color( bc.getRed()/255f,bc.getGreen()/255f,bc.getBlue()/255f,0.9f) );
		
		if (handler==null){ 
			
			// resultPanelsjPopupMenu = new JPopupMenu();
			handler = new ItemHandler();
		
			resultPanelsjPopupMenu.add( getMenuPopup(0, handler, "open") );
			resultPanelsjPopupMenu.add( getMenuPopup(1, handler, "store permanently") );
			resultPanelsjPopupMenu.add( getMenuPopup(2, handler, "remove") );
			resultPanelsjPopupMenu.add( getMenuPopup(3, handler, "remove & clear traces") );
			resultPanelsjPopupMenu.add( getMenuPopup(4, handler, "exclude domain") );
			
			/*
			 * these are handled by PopupItemsSelectionHandler.handlingItemSelection()
			 */
		}
		
		
		
		
		wrappingwindow.getRootPane().add(resultPanelsjPopupMenu);
		
		int wwcCount = wrappingwindow.getRootPane().getComponents().length;
		Component[] wwc = wrappingwindow.getRootPane().getComponents();

		for (int i=0;i<wwc.length;i++){
			
			String cn = wwc[i].getClass().getSimpleName().toLowerCase();
			if ((wwc[i] instanceof JPopupMenu ) || (cn.contains("popup"))){
				wwPopup = wwc[i]; 
			}
			if ((wwc[i] instanceof JPanel) || (cn.contains("jpanel"))){
				((JPanel)wwc[i]).setOpaque(true);
				((JPanel)wwc[i]).setBackground( new Color(0.94f,0.94f,0.98f,0.01f));
			}
		}

	}
	
	
	// ------------------------------------------------------------------------
	
	private JMenuItem getMenuPopup( final int index, ItemHandler handler, String caption) {
		
		if ((index<0) && (index>=popupItems.length)){
			return null;
		}
		
		JMenuItem mItem = popupItems[index];
		
		
		if( mItem == null) {
			mItem = new JMenuItem(); 
			
			String str = caption.replaceAll(" ", "_");
			mItem.setName("popupItem-"+str);
			
			mItem.setText(caption);
			mItem.addActionListener(handler);
			
			popupItems[index] = mItem;
			mappedItems.put(mItem,index);
			/*
			mItem.addMouseListener(new MouseAdapter() {
				public void mouseClicked(MouseEvent evt) {
					popupItemMouseClicked(index, evt);
				}
			});
			*/
		}
		return mItem;

	}

	private class ItemHandler implements ActionListener {
	
		public void actionPerformed(ActionEvent e) {
			// determine which menu item was selected
			// System.out.println("MenuItem action detected : " + e);

			wrappingwindow.setSize(1,1);
			wrappingwindow.setVisible(false);
			appCommons.getPanelProducer().getPanels().getItem(clickedPanelIndex).repaint() ;
		
			// mappedItems
			
			for (int i = 0; i < popupItems.length; i++) {
				Object miObj = e.getSource() ;
				
				if (miObj == popupItems[i]) {

					out.print(2, "popup item " + i + " clicked");
					new PopupItemsSelectionHandler( appCommons, clickedPanelIndex, i ) ;
					wrappingwindow.setSize( 0,0) ;
					return;
				}
			}
		}
	}
  


	public JPopupMenu getResultPanelsjPopupMenu() {
		return resultPanelsjPopupMenu;
	}

	public JPopupMenu getPanelPopupMenu() {
		return resultPanelsjPopupMenu;
	}


	public void show(int panelIndex, JEditorPane textPane, MouseEvent mevt) {
		//
		out.print(2, "showing popup on panel "+panelIndex+" , "+mevt);
		
		clickedPanelIndex = panelIndex;
		
		int ty = textPane.getLocationOnScreen().y;
		int tx = textPane.getLocationOnScreen().x;
		
		wrappingwindow.setSize( 1,1) ;
		wrappingwindow.setVisible(true);
		// wrappingwindow.setSize( wwLastWidth, wwLastHeight) ;		
		wrappingwindow.setLocation( tx+mevt.getX(), ty+mevt.getY()) ;
		
		((JPopupMenu)wwPopup).show(wrappingwindow,1,1);
		
		Rectangle visibleRect = new Rectangle();
		resultPanelsjPopupMenu.computeVisibleRect(visibleRect);
		visibleRect = resultPanelsjPopupMenu.getVisibleRect() ;
		
		wwLastWidth  = visibleRect.width ;
		wwLastHeight = visibleRect.height ;
		
		wrappingwindow.setSize( wwLastWidth, wwLastHeight) ;
		((JPopupMenu)wwPopup).show(wrappingwindow,1,1);
		
		
	}
	


	//Define PopupMenuListener
	class RPanelMenuListener implements PopupMenuListener {
	  public void popupMenuCanceled(PopupMenuEvent popupMenuEvent) {
	    // System.out.println("Canceled");
	    
	    hide();
	    
	    appCommons.getPanelProducer().getPanels().getItem(clickedPanelIndex).repaint();
	    appCommons.getWindowGui().getjPanelScrollWrapFoundStack().repaint();
	    appCommons.getWindowGui().getMainFrame().repaint();
	  }

	  public void popupMenuWillBecomeInvisible(PopupMenuEvent popupMenuEvent) {
	    // System.out.println("Becoming Invisible");
	    hide();
	    
	  }

	  public void popupMenuWillBecomeVisible(PopupMenuEvent popupMenuEvent) {
	    // System.out.println("Becoming Visible");
	  }
	}
}

